package com.homework.news

import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import com.google.gson.Gson
import org.json.JSONObject
import java.lang.Exception
import java.io.InputStreamReader

import java.io.BufferedReader
import java.net.HttpURLConnection

import java.net.URL
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import com.google.gson.reflect.TypeToken


class MainActivity : AppCompatActivity(), View.OnClickListener, AdapterView.OnItemClickListener {
    //sjsjjsjs
    var top: TextView? = null
    var guonei: TextView? = null
    var guoji: TextView? = null
    var yule: TextView? = null
    var tiyu: TextView? = null
    var junshi: TextView? = null
    var keji: TextView? = null
    var caijing: TextView? = null
    var home: Button? = null
    var video: Button? = null
    var my: Button? = null

    //ssss
    var dataList: List<News> = ArrayList<News>()
    var listView: ListView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT > 9) {
            val policy = ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)
        }
        getView()
        top?.setOnClickListener(this)
        guonei?.setOnClickListener(this)
        guoji?.setOnClickListener(this)
        yule?.setOnClickListener(this)
        tiyu?.setOnClickListener(this)
        junshi?.setOnClickListener(this)
        keji?.setOnClickListener(this)
        caijing?.setOnClickListener(this)
        home?.setOnClickListener(this)
        video?.setOnClickListener(this)
        my?.setOnClickListener(this)
        var responseData =
            getHttpResult("http://v.juhe.cn/toutiao/index?type=top&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
        if (responseData != null) {
            var jsonArray = JSONObject(responseData);
            var result = jsonArray.get("result").toString()
            //Log.i("result", result)
            var data = JSONObject(result).get("data").toString()
            var list: List<News> = parseJSONWithGSON(data)
            dataList = list
            println(dataList.size)
            println("获得数据")
            setListView(dataList)
        } else {
            println("数据获取失败")
        }
        listView?.setOnItemClickListener(this)
    }

    private fun getView() {
        top = findViewById(R.id.top)
        guonei = findViewById(R.id.guonei)
        guoji = findViewById(R.id.guoji)
        yule = findViewById(R.id.yule)
        tiyu = findViewById(R.id.tiyu)
        junshi = findViewById(R.id.junshi)
        keji = findViewById(R.id.keji)
        caijing = findViewById(R.id.caijing)
        listView = findViewById(R.id.listView)
        home = findViewById(R.id.home)
        video = findViewById(R.id.video)
        my = findViewById(R.id.my)
    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        var news = dataList[position]
        var intent = Intent(this, NewsDetailActivity::class.java)
        intent.putExtra("news", news)
        startActivity(intent)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.home -> {
                var intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
            }
            R.id.video -> {
                var intent = Intent(this, VideoActivity::class.java)
                startActivity(intent)
            }
            R.id.top -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=top&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.guonei -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=guonei&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.guoji -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=guoji&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.yule -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=yule&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.tiyu -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=tiyu&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.junshi -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=junshi&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.keji -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=keji&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
            R.id.caijing -> {
                println("发起请求")
                var responseData =
                    getHttpResult("http://v.juhe.cn/toutiao/index?type=caijing&key=fb8892fddef5be07d42d4f920ad76a87&is_filter=1")
                if (responseData != null) {
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    var list: List<News> = parseJSONWithGSON(data)
                    dataList = list
                    println(dataList.size)
                    println("获得数据")
                    setListView(dataList)
                } else {
                    println("数据获取失败")
                }
            }
        }
    }

    private fun setListView(data: List<News>) {
        val adapter = NewsAdapter(this, R.layout.news_item, data)
        listView?.adapter = adapter
    }

    /*private fun sendRequestWithOkHttp(type: String): List<News> {
        var list: List<News> = ArrayList<News>()
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://v.juhe.cn/toutiao/index?type=" + type + "&key=fb8892fddef5be07d42d4f920ad76a87")
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null){
                    var jsonArray = JSONObject(responseData);
                    var result = jsonArray.get("result").toString()
                    //Log.i("result", result)
                    var data = JSONObject(result).get("data").toString()
                    //Log.i("data", data)
                    list = parseJSONWithGSON(data)
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
        return list
    }*/

    fun getHttpResult(urlStr: String?): String? {
        return try {
            val url = URL(urlStr)
            val connect = url.openConnection() as HttpURLConnection
            val input = connect.inputStream
            val `in` = BufferedReader(InputStreamReader(input))
            var line: String? = null
            println(connect.responseCode)
            val sb = StringBuffer()
            while (`in`.readLine().also { line = it } != null) {
                sb.append(line)
            }
            sb.toString()
        } catch (e: Exception) {
            println(e.toString())
            null
        }
    }

    private fun parseJSONWithGSON(jsonData: String): List<News> {
        val gson = Gson()
//        val typeOf = object : TypeToken<List<News>>() {}.type
        val typeOf = object : TypeToken<List<News>>() {}.type
        val newsList = gson.fromJson<List<News>>(jsonData, typeOf)
        println(newsList[1].title)
        return newsList;
    }
}

